import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Car } from 'src/module/admin/car/entities/car.entity';
import { CarPhoto } from 'src/module/admin/car_photo/entities/car_photo.entity';
import { User } from 'src/module/admin/user/entities/user.entity';
import { Not, Repository } from 'typeorm';

@Injectable()
export class CarService {
  constructor(
    @InjectRepository(Car) private readonly carRepository: Repository<Car>,
    @InjectRepository(CarPhoto)
    private readonly carPhotoRepository: Repository<CarPhoto>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  // create(createCarDto: CreateCarDto) {
  //   return 'This action adds a new car';
  // }

  async findCarByUserId(userId) {
    const res = await this.carRepository.find({
      select: [
        'id',
        'primary_id',
        'brand',
        'license_plate',
        'shape',
        'color',
        'displacement',
      ],
      where: { user: { id: userId }, isDelete: Not(true) },
    });

    return res;
  }

  async addCarPhotos(carId, params: any) {
    const car = await this.carRepository.findOne({
      where: { id: carId },
    });

    try {
      Object.values(params).forEach(async (item: string) => {
        const carPhoto = new CarPhoto();
        carPhoto.url = item;
        carPhoto.car = car;
        await this.carPhotoRepository.save(carPhoto);
      });
      return { msg: '上传成功' };
    } catch (e) {
      return {
        msg: '上传错误',
      };
    }
  }

  // 添加车辆
  async addCar(userId, params) {
    const user = await this.userRepository.findOne({
      where: { id: userId },
    });
    const car = new Car();
    car.brand = params.brand;
    car.license_plate = params.license_plate;
    car.color = params.color;
    car.displacement = params.displacement;
    car.shape = params.shape;
    car.status = '0';
    car.user = user;

    return this.carRepository.save(car);
  }

  findOne(id: number) {
    return `This action returns a #${id} car`;
  }

  // update(id: number, updateCarDto: UpdateCarDto) {
  //   return `This action updates a #${id} car`;
  // }

  remove(id: number) {
    return `This action removes a #${id} car`;
  }
}
